package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;


import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.RedisConstants.LOCK_SHOP_KEY;

/**
 * @program: hmdp
 * @ClassName CacheCilent
 * @description:
 * @author: oldTea
 * @create: 2024-06-03 19:54
 * @Version 1.0
 **/
@Component
@Slf4j
public class CacheClient {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static  final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * t
     * @param key
     * @param value
     * @param time
     * @param unit
     */
    public void set(String key, Object value,Long time,TimeUnit unit){
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
    }
    public void setLogicalExpire(String key,Object value,Long time,TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        redisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData));
    }

    public Boolean tryLock(String key){
        Boolean b = redisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(b);
    }

    /**
     * 释放锁
     * @param key
     */
    public void unLock(String key){
        redisTemplate.delete(key);
    }

    /**
     * 通过缓存空对象的方法解决缓存穿透
     * @param id
     * @return
     */
    public  <R,ID> R  getShopByThrough(String prefixKey, ID id, Class<R> type, Function<ID,R> fallBack,
                                       Long time,TimeUnit unit){
        String key = prefixKey + id;
        //从redis中查询
        String jsonShop = redisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(jsonShop)){
            R r = JSONUtil.toBean(jsonShop, type);
            return r;
        }
        if(jsonShop != null){
            return null;
        }
        //此处不同的类需要不同的方法进行查询，因此用函数式编程，传动态方法
        R r = fallBack.apply(id);
        if(r == null){
            //缓存空对象
            redisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }
        this.set(key,r,time,unit);
        return r;

    }

    /**
     * 设置热点数据不用再仅需缓存空对象
     * @param id
     * @return
     */
    public <ID,R> R getShopByLogicalExpire(String prefixKey, ID id, Class<R> type, Function<ID,R> fallBack,
                                       Long time,TimeUnit unit){

        String key = prefixKey + id;
        //从redis中查询
        String jsonShop = redisTemplate.opsForValue().get(prefixKey + id);
        if(StrUtil.isBlank(jsonShop)){
            return null;

        }
        RedisData redisData = JSONUtil.toBean(jsonShop, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        //没过期先返回老数据
        if (expireTime.isAfter(LocalDateTime.now())) {
            return r;
        }

        Boolean b = tryLock(LOCK_SHOP_KEY + id);
        //获取锁失败，直接返回旧数据
        if (!b){
            return r;
        }
        //获取锁成功再次查询缓存中是否有数据
        jsonShop = redisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        if(StrUtil.isBlank(jsonShop)){
            return null;
        }
        //开启线程重建缓存
        CACHE_REBUILD_EXECUTOR.submit(() ->{
            try {
                R apply = fallBack.apply(id);
                this.setLogicalExpire(key,apply,time,unit);
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                unLock(LOCK_SHOP_KEY +id);
            }

        });
        return r;

    }





}